# coding=utf-8
__author__ = 'zzy'

from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Convolution2D, MaxPooling2D
from keras.utils import np_utils
import numpy as np
import pandas as pd


def cnn():
    model = Sequential()
    model.add(Convolution2D(
        16, 3, 3, border_mode='valid', input_shape=(28, 28, 1)))
    model.add(Activation('relu'))
    model.add(Convolution2D(16,3,3))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(128))
    model.add(Activation('relu'))
    model.add(Dropout(0.25))
    model.add(Dense(64))
    model.add(Activation('relu'))
    model.add(Dropout(0.25))
    model.add(Dense(10))
    model.add(Activation('softmax'))
    model.compile(loss='categorical_crossentropy',
                  optimizer='adadelta', metrics=['accuracy'])
    return model


def data():
    train = pd.read_csv('train.csv')
    test_images = (pd.read_csv("test.csv").values).astype('float32')
    test_images = test_images.reshape(test_images.shape[0], 28, 28, 1)
    train_images = (train.ix[:, 1:].values).astype('float32')
    train_labels = train.ix[:, 0].values.astype('int32')
    train_images = train_images.reshape(train_images.shape[0], 28, 28, 1)
    train_images = train_images / 255
    train_labels = np_utils.to_categorical(train_labels)
    return train_images, train_labels, test_images


def out():
    model.fit(train_images, train_labels, epochs=12,
              validation_split=0.001, batch_size=64)
    p = model.predict_classes(test_images, verbose=0)
    sub = pd.DataFrame({'ImageId': list(range(1, len(p) + 1)), 'Label': p})
    sub.to_csv('re.csv', index=False, header=True)
